package com.csyf.manager.service.impl;

import com.csyf.manager.dao.SysAgentChannelDao;
import com.csyf.manager.dao.SysAliAccountDao;
import com.csyf.manager.dao.SysMerchDao;
import com.csyf.manager.dao.SysWithdrawalRecordDao;
import com.csyf.manager.entity.SysAgentChannel;
import com.csyf.manager.entity.SysAliAccount;
import com.csyf.manager.entity.SysMerchant;
import com.csyf.manager.exception.ApiValidateException;
import com.csyf.manager.service.SysAccountBalanceBiz;
import com.csyf.manager.service.SysAliAccountBiz;
import com.csyf.manager.utils.page.JqGridVo;
import com.csyf.manager.utils.page.PageUtils;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: casper
 * @Description: 支付宝账户BizImpl
 * @Date: Created in 2018/10/25 18:53
 */
@Slf4j
@Service
public class SysAliAccountBizImpl implements SysAliAccountBiz {

    @Autowired
    private SysAliAccountDao sysAliAccountDao;


    @Autowired
    private SysAgentChannelDao sysAgentChannelDao;

    @Autowired
    private SysMerchDao sysMerchDao;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysAccountBalanceBiz sysAccountBalanceBiz;


    @Autowired
    private SysWithdrawalRecordDao sysWithdrawalRecordDao;

    /**
     * 查询支付宝账户列表
     *
     * @param vo
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public JqGridVo querydata(SysAliAccount vo, Integer pageIndex, Integer pageSize) {

        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("id desc");

        Example example = new Example(SysAliAccount.class);
        Example.Criteria criteria = example.createCriteria();
        PageUtils.andEqualTo(criteria, "channelNo", vo.getChannelNo());
        PageUtils.andEqualTo(criteria, "appid", vo.getAppid());

        List<SysAliAccount> select = sysAliAccountDao.selectByExample(example);
        return PageUtils.pasrJqGrid(select);
    }


    @Override
    public JqGridVo queryAccountBalance(SysAliAccount vo, Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        PageHelper.orderBy("id desc");

        Example example = new Example(SysAliAccount.class);
        Example.Criteria criteria = example.createCriteria();
        PageUtils.andEqualTo(criteria, "channelNo", vo.getChannelNo());

        List<SysAliAccount> select = sysAliAccountDao.selectByExample(example);

        String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String yyyyMMdd2 = new SimpleDateFormat("yyyy-MM-dd").format(new Date());


        for (SysAliAccount sysAliAccount : select) {
            String srcmchkey = "trade:srcmch:" + yyyyMMdd + ":" + sysAliAccount.getAppid();
            String srcmchkey_profit = "trade:srcmch_profit:" + yyyyMMdd + ":" + sysAliAccount.getAppid();
            String s = redisService.get(srcmchkey);
            sysAliAccount.setTodaymoney(null == s ? BigDecimal.ZERO : new BigDecimal(s));

            String s1 = redisService.get(srcmchkey_profit);

            BigDecimal profit = null == s1 ? BigDecimal.ZERO : new BigDecimal(s1);
            BigDecimal bigDecimal = sysAccountBalanceBiz.queryBalance(sysAliAccount.getAppid(), 1);
            BigDecimal totalCase = sysWithdrawalRecordDao.queryTotalCase(sysAliAccount.getAppid(), yyyyMMdd2);
            sysAliAccount.setAccountMoney(bigDecimal.add(profit).subtract(totalCase));
        }
        return PageUtils.pasrJqGrid(select);
    }


    @Override
    public List<SysAliAccount> select(SysAliAccount vo) {
        return sysAliAccountDao.select(vo);
    }

    /**
     * 保存支付宝账户
     *
     * @param vo
     */
    @Override
    public void saveAccount(SysAliAccount vo) throws Exception {

        SysAliAccount byAppid = findByAppid(vo.getAppid());
        if (null != byAppid) {
            throw new ApiValidateException("appid 已经存在，请勿重复增加");
        }
        vo.setChannelNo("alipay");
        vo.setChannelStatus(1);
        vo.setQuotaStatus(0);
        vo.setWithdrawalStatus(0);
        sysAliAccountDao.insertSelective(vo);
    }

    /**
     * 根据id查询支付宝账户
     *
     * @param id
     * @return
     */
    @Override
    public SysAliAccount findById(Long id) {
        return sysAliAccountDao.selectByPrimaryKey(id);
    }


    @Override
    public SysAliAccount findByAppid(String appid) {
        SysAliAccount sysAliAccount = new SysAliAccount();
        sysAliAccount.setAppid(appid);
        return sysAliAccountDao.selectOne(sysAliAccount);
    }

    /**
     * 修改支付宝账户
     *
     * @param vo
     * @return
     */
    @Override
    public int updateAccount(SysAliAccount vo) {
        return sysAliAccountDao.updateByPrimaryKeySelective(vo);
    }

    /**
     * 删除支付宝账户
     *
     * @param accountId
     */
    @Override
    public void deleteAccount(Long accountId) {
        sysAliAccountDao.deleteByPrimaryKey(accountId);
    }

    @Override
    public void stopaccount(Long id) {

        SysAliAccount sysAliAccount = new SysAliAccount();
        sysAliAccount.setId(id);
        SysAliAccount selectOne = sysAliAccountDao.selectOne(sysAliAccount);
        selectOne.setChannelStatus(0);
        sysAliAccountDao.updateByPrimaryKeySelective(selectOne);

        SysAgentChannel sysAgentChannel = new SysAgentChannel();
        sysAgentChannel.setMerchantNo(selectOne.getAppid());
        List<SysAgentChannel> select = sysAgentChannelDao.select(sysAgentChannel);
        for (SysAgentChannel entry : select) {
            entry.setStatus(0);
            sysAgentChannelDao.updateByPrimaryKeySelective(entry);
        }
    }


    @Override
    public void startaccount(Long id) {
        SysAliAccount sysAliAccount = new SysAliAccount();
        sysAliAccount.setId(id);
        SysAliAccount selectOne = sysAliAccountDao.selectOne(sysAliAccount);
        selectOne.setChannelStatus(1);
        sysAliAccountDao.updateByPrimaryKeySelective(selectOne);


        SysAgentChannel sysAgentChannel = new SysAgentChannel();
        sysAgentChannel.setMerchantNo(selectOne.getAppid());
        List<SysAgentChannel> select = sysAgentChannelDao.select(sysAgentChannel);
        for (SysAgentChannel entry : select) {
            entry.setStatus(1);
            sysAgentChannelDao.updateByPrimaryKeySelective(entry);
        }
    }


    /**
     * 满额
     *
     * @param appid
     */
    @Override
    public void quotaAll(String appid) {
        SysAliAccount sysAliAccount = new SysAliAccount();
        sysAliAccount.setAppid(appid);
        SysAliAccount selectOne = sysAliAccountDao.selectOne(sysAliAccount);
        selectOne.setChannelStatus(0);
        selectOne.setQuotaStatus(1);
        selectOne.setWithdrawalStatus(1);
        sysAliAccountDao.updateByPrimaryKeySelective(selectOne);


        SysAgentChannel sysAgentChannel = new SysAgentChannel();
        sysAgentChannel.setMerchantNo(selectOne.getAppid());
        List<SysAgentChannel> select = sysAgentChannelDao.select(sysAgentChannel);
        for (SysAgentChannel entry : select) {
            entry.setStatus(0);
            sysAgentChannelDao.updateByPrimaryKeySelective(entry);
        }
    }


    /**
     * 额度清0
     *
     * @param id
     */
    @Override
    public void clearquota(Long id) {

        SysAliAccount sysAliAccount = new SysAliAccount();
        sysAliAccount.setId(id);
        SysAliAccount selectOne = sysAliAccountDao.selectOne(sysAliAccount);

        selectOne.setChannelStatus(1);
        selectOne.setQuotaStatus(0);
        selectOne.setWithdrawalStatus(0);
        sysAliAccountDao.updateByPrimaryKeySelective(selectOne);


        //商户通道开启
        SysAgentChannel sysAgentChannel = new SysAgentChannel();
        sysAgentChannel.setMerchantNo(selectOne.getAppid());
        List<SysAgentChannel> select = sysAgentChannelDao.select(sysAgentChannel);
        for (SysAgentChannel entry : select) {
            entry.setStatus(1);
            sysAgentChannelDao.updateByPrimaryKeySelective(entry);
        }
    }


    /**
     * @param id 账号列表ID
     * @return
     */
    @Override
    public ArrayList<Map> merhcantlist(Long id) {


        SysAliAccount byId = findById(id);

        SysMerchant sysAgent = new SysMerchant();
        sysAgent.setMerchStatus(1);
        List<SysMerchant> sysAgents = sysMerchDao.select(sysAgent);

        SysAgentChannel sysAgentChannel = new SysAgentChannel();
        sysAgentChannel.setMerchantNo(byId.getAppid());
        List<SysAgentChannel> select = sysAgentChannelDao.select(sysAgentChannel);
        HashSet<String> objects = new HashSet<>();

        for (SysAgentChannel agentChannel : select) {
            objects.add(agentChannel.getMchId());
        }

        ArrayList<Map> maps = new ArrayList<>();
        for (SysMerchant agent : sysAgents) {

            if (objects.contains(agent.getMerchMerchantNo())) {
                continue;
            } else {
                HashMap<String, String> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("id", String.valueOf(agent.getId()));
                objectObjectHashMap.put("name", agent.getMerchName());
                maps.add(objectObjectHashMap);
            }
        }

        return maps;
    }


    @Override
    public void issueMerchant(Long id, Long agentId, String rate) {
        SysAliAccount byId = findById(id);

        SysMerchant sysAgent = new SysMerchant();
        sysAgent.setId(agentId);
        SysMerchant selectOne = sysMerchDao.selectOne(sysAgent);

        SysAgentChannel sysAgentChannel = new SysAgentChannel();
        sysAgentChannel.setMerchantNo(byId.getAppid());
        sysAgentChannel.setMchId(selectOne.getMerchMerchantNo());
        sysAgentChannel.setAgentId(selectOne.getId());
        sysAgentChannel.setChannelName(byId.getChannelNo());
        sysAgentChannel.setMerchantNo(byId.getAppid());
        sysAgentChannel.setSignKey(byId.getPrivateKey());
        sysAgentChannel.setStatus(1);
        sysAgentChannel.setPublicKey(byId.getPublicKey());
        sysAgentChannel.setRate(new BigDecimal(rate));
        sysAgentChannel.setFree(BigDecimal.ZERO);
        sysAgentChannel.setCostRate(byId.getChannelRate());
        sysAgentChannelDao.insertSelective(sysAgentChannel);
    }
}
